package com.stardata.liangshisq.tcslmon.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.stardata.liangshisq.tcslmon.entity.*;
import com.stardata.liangshisq.tcslmon.service.*;
import com.stardata.liangshisq.tcslmon.util.CommonConstants;
import com.stardata.liangshisq.tcslmon.util.JSONUtil;
import com.stardata.liangshisq.tcslmon.util.NoTimeArchItemUtil;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;


/**
 * 将数据从各个门店同步到服务端
 * 主要同步数据有
 * <p>
 * biz_kc_ksc
 * biz_bs_order
 */

@Component
@AllArgsConstructor
public class OrderPushTask {

    private final String DATA_PUSH_EXCHANGE = "data.sender.exchange";

    private final String DATA_ORDER_TOPIC = "data.sender.order.topic";

    private final String DATA_KSC_TOPIC = "data.sender.ksc.topic";

    private final String DATA_ARCH_ITEM_TOPIC = "data.sender.arch.item.topic";

    private final String DATA_ARCH_POINT_TOPIC = "data.sender.arch.point.topic";


    private final KcKscService kcKscService;
    private final BizBsService bizBsService;

    private final OrderPushService orderPushService;

    private final OrderInfoService orderInfoService;

    private final RabbitTemplate rabbitTemplate;

    private final TbBizBsTimeService tbBizBsTimeService;

    private final TbKcKscTimeService tbKcKscTimeService;

    /**
     * biz_kc 同步：订单信息的同步
     */
    @Scheduled(cron = "0/50 * * * * ?")
    public void doBizBsDataSend() {
        try {
            // 1. 查询待统计的数据记录
            QueryWrapper<TbBizBsTime> wrapper = new QueryWrapper<TbBizBsTime>();
            LocalDateTime now = LocalDateTime.now();
            wrapper.between("open_time", now.with(LocalTime.MIN), now.with(LocalTime.MAX));
            wrapper.eq("send_status", 0);
            wrapper.orderBy(true, true, "modify_time");
            wrapper.last("limit 10");
            //查询结算时间不为空，且同步状态不等于2的订单信息
            List<TbBizBsTime> tbBizBsTimeList = tbBizBsTimeService.list(wrapper);
            if (ObjectUtils.isEmpty(tbBizBsTimeList)) {
                return;
            }
            List<Long> bsIds = new ArrayList<>();
            Map<Long, TbBizBsTime> tbBizBsTimeHashMap = new HashMap<>();
            for (TbBizBsTime tbBizBsTime : tbBizBsTimeList) {
                bsIds.add(tbBizBsTime.getId());
                tbBizBsTimeHashMap.put(tbBizBsTime.getId(), tbBizBsTime);
            }
            // 2.获取数据的biz_bs信息；
            List<BizBs> bizBsList = orderInfoService.querySendData(bsIds);
            if (bizBsList == null || bizBsList.isEmpty()) {
                return;
            }
            for (BizBs bizBs : bizBsList) {
                // 3. 开始同步数据
                TbBizBsTime tbBizBsTime = tbBizBsTimeHashMap.get(bizBs.getId());
                if (tbBizBsTime == null) {
                    return;
                }
                // biz_bs同步
                rabbitTemplate.convertAndSend(DATA_PUSH_EXCHANGE, DATA_ORDER_TOPIC, JSONUtil.toJSONString(bizBs));
                //4. 添加逻辑 如果是当天的数据，且未结算  则is_send不设置为1; 已经结算或者订单开始已经超过8小时，则默认表示已经结算
                Integer state = bizBs.getState();
                long hours = Duration.between(bizBs.getOpenTime(), LocalDateTime.now()).toHours();//相差的小时数
                if (state == 1 || hours > 8) {
                    tbBizBsTime.setSendStatus(1L);
                    tbBizBsTime.setModifyTime(LocalDateTime.now());
                    tbBizBsTimeService.updateById(tbBizBsTime);
                } else {
                    bizBs.setModifyTime(LocalDateTime.now());
                    tbBizBsTimeService.updateById(tbBizBsTime);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    /**
     * 菜品信息的推送
     */
    @Scheduled(cron = "0/50 * * * * ?")
    public void doBizKcKscDataSend() {
        try {
            // 1. 查询待统计的数据记录，ksc的数据
            QueryWrapper<TbKcKscTime> wrapper = new QueryWrapper<TbKcKscTime>();
            LocalDateTime now = LocalDateTime.now();
            wrapper.between("call_up_time", now.with(LocalTime.MIN), now.with(LocalTime.MAX));
            wrapper.eq("send_status", 0);
            wrapper.orderBy(true, true, "modify_time");
            wrapper.last("limit 10");
            List<TbKcKscTime> tbKcKscTimeList = tbKcKscTimeService.list(wrapper);
            List<Long> kscIds = new ArrayList<>();
            Map<Long, TbKcKscTime> tbKcKscTimeHashMap = new HashMap<>();
            for (TbKcKscTime item : tbKcKscTimeList) {
                kscIds.add(item.getId());
                tbKcKscTimeHashMap.put(item.getId(), item);
            }
            //2.查询结算时间不为空，且同步状态不等于2的订单信息
            QueryWrapper<KcKsc> kscWrapper = new QueryWrapper<KcKsc>();
            if (!kscIds.isEmpty()) {
                kscWrapper.in("id", kscIds);
            } else {
                return;
            }
            List<KcKsc> kcKscList = kcKscService.list(kscWrapper);
            for (KcKsc kcKsc : kcKscList) {
                // 3. 开始同步数据
                TbKcKscTime tbKcKscTime = tbKcKscTimeHashMap.get(kcKsc.getId());
                if (tbKcKscTime == null) {
                    return;
                }
                // biz_kc 同步
                rabbitTemplate.convertAndSend(DATA_PUSH_EXCHANGE, DATA_KSC_TOPIC, JSONUtil.toJSONString(kcKsc));
                long hours = Duration.between(kcKsc.getCallUpTime(), LocalDateTime.now()).toHours();//相差的小时数
                if (kcKsc.getKitchenFlg().equals(CommonConstants.KitchenFlg.PRODUCED)) {
                    // 菜品已经传了
                    tbKcKscTime.setSendStatus(1L);
                    tbKcKscTime.setModifyTime(LocalDateTime.now());
                    tbKcKscTimeService.updateById(tbKcKscTime);
                } else if (kcKsc.getLastQty().doubleValue() < 0.001) { // 退单的 不需要核算
                    tbKcKscTime.setSendStatus(1L);
                    tbKcKscTime.setModifyTime(LocalDateTime.now());
                    tbKcKscTimeService.updateById(tbKcKscTime);
                } else if (hours > 8) { // 菜品单子大于8H的
                    tbKcKscTime.setSendStatus(1L);
                    tbKcKscTime.setModifyTime(LocalDateTime.now());
                    tbKcKscTimeService.updateById(tbKcKscTime);
                } else if (NoTimeArchItemUtil.noArchItem().contains(kcKsc.getItemId())) {
                    tbKcKscTime.setSendStatus(1L);
                    tbKcKscTime.setModifyTime(LocalDateTime.now());
                    tbKcKscTimeService.updateById(tbKcKscTime);
                } else {
                    tbKcKscTime.setModifyTime(LocalDateTime.now());
                    tbKcKscTimeService.updateById(tbKcKscTime);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    /**
     * 菜品和point的信息同步
     */
    @Scheduled(cron = "0 0 10,16 * * ?")
    public void doArchItemSend() {
        List<ArchItem> archItemList = orderPushService.sendArchItem();
        List<ArchPoint> ArchPoint = orderPushService.sendArchPoint();
        for (ArchItem archItem : archItemList) {
            rabbitTemplate.convertAndSend(DATA_PUSH_EXCHANGE, DATA_ARCH_ITEM_TOPIC, JSONUtil.toJSONString(archItem));
        }
        for (ArchPoint archPoint : ArchPoint) {
            rabbitTemplate.convertAndSend(DATA_PUSH_EXCHANGE, DATA_ARCH_POINT_TOPIC, JSONUtil.toJSONString(archPoint));
        }
    }
}
